﻿using UnityEngine;
using System.Collections;

public class AimingSystem : MonoBehaviour 
{
	LineRenderer line;
	
	[SerializeField] WeaponsScript curWeapon = null;
	public LineRenderer sightLine;
	
	[SerializeField] int segmentCount = 20;
	
	[SerializeField] float segmentScale = 1;
	
	private Collider _hitObject;
	public Collider hitObject { get {return _hitObject;} }
	
	void FixedUpdate()
	{
		simulatePath();
	}
	
	void simulatePath()
	{
		Vector3[] segments =  new Vector3[segmentCount];
		
		segments[0] = curWeapon.bulletsSpawnPoint.position;
		
		Vector3 segVelocity = curWeapon.bulletsSpawnPoint.forward.normalized * curWeapon.BulletForce * Timing.CustomDeltaTime();
		
		_hitObject = null;
		
		for(int i = 1; i < segmentCount; i++)
		{
			float segTime = (segVelocity.sqrMagnitude != 0) ? segmentScale / segVelocity.magnitude : 0;
			
			segVelocity = segVelocity + CenterOfGravity.NewGravityDirection(transform.position) * segTime;
			
			RaycastHit hit;
			if (Physics.SphereCast(segments[i - 1], 0.5f * 0.35f,segVelocity, out hit, segmentScale))
			{
				segments[i] = segments[i - 1];
// 
				/*
				 * Here you could check if the object hit by the Raycast had some property - was 
				 * sticky, would cause the ball to explode, or was another ball in the air for 
				 * instance. You could then end the simulation by setting all further points to 
				 * this last point and then breaking this for loop.
				 */
			}
			// If our raycast hit no objects, then set the next position to the last one plus v*t
			else
			{
				segments[i] = segments[i - 1] + segVelocity * segTime;
			}
		}
		sightLine.SetVertexCount(segmentCount);
	
		for (int i = 0; i < segmentCount; i++)
			sightLine.SetPosition(i, segments[i]);
	}
}
